package io.github.annyylxyms.gyncache.command;

import io.github.annyylxyms.gyncache.core.Command;
import io.github.annyylxyms.gyncache.core.GynCache;
import io.github.annyylxyms.gyncache.core.Reply;

/**
 *
 * @author Anny
 * @date 2025/1/15 17:10
 */
public class LpopCommand implements Command {
    @Override
    public String name() {
        return "LPOP";
    }

    @Override
    public Reply<?> exec(GynCache cache, String[] args) {
        String key = getKey(args);
        //默认pop count 是1
        int count = 1;
        if (args.length > 6) {
            //如果传了count，返回数组
            /**
             * lpop l1 2
             * 1) "4"
             * 2) "3"
             */
            String var = getVal(args);
            count = Integer.parseInt(var);
            return Reply.array(cache.lpop(key, count));
        }

        //如果没传count，要不是空，要不是单个元素
        /**
         * lpop l1
         * "5"
         */
        String[] lpop = cache.lpop(key, count);
        return Reply.bulkString(lpop == null ? null : lpop[0]);
    }
}
